<template>
  <div>
    <el-form ref="myform" :model="formItem" :rules="rules" label-width="100px" size="mini">
      <el-form-item label="单位名称" prop="name">
        <el-input v-model="formItem.name" placeholder="请输入单位名称" />
      </el-form-item>
      <el-form-item label="驻场人员" prop="residentCodeArray">
        <el-select v-model="formItem.residentCodeArray" multiple filterable placeholder="请选择驻场人员">
          <el-option v-for="item in availableResidentUsers" :key="item.username" :label="item.name" :value="item.username" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="机动人员" prop="userCodes">
        <el-select v-model="formItem.userCodes" multiple filterable placeholder="请选择机动人员">
          <el-option v-for="item in availableUsers" :key="item.username" :label="item.name" :value="item.username" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="精度" prop="lng">
        <el-input-number v-model="formItem.lng" :precision="6" :step="0.1" />
      </el-form-item>
      <el-form-item label="维度" prop="lat">
        <el-input-number v-model="formItem.lat" :precision="6" :step="0.1" />
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
const formRules = {
  name: [{ required: true, message: '公司名称不能为空', trigger: 'blur' }],
  residentCodeArray: [{ required: true, message: '驻场人员不能为空', trigger: 'blur' }]
}

import { create, update, detail } from '@neu/dcom-ui/api/institutions'
import { list as userList } from '@neu/auth-ui/api/user'
// 定义一个表单原始项
const formItem = {
  // 公司名称
  name: '',
  // 公司编码
  code: '',
  // 驻场人员名称
  residentCodeArray: [],
  // 关联机动人员编码
  userCodes: [],
  lng: 0,
  lat: 0
}
export default {
  name: 'InstitutionsEditForm',
  props: {
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      // 编辑的表单内容
      formItem: {
        ...formItem
      },
      // 机动人员列表
      availableUsers: [],
      // 驻场人员集合
      availableResidentUsers: [],
      // 表单验证规则
      rules: { ...formRules }
    }
  },
  watch: {
    // 监控id的变化，初始化表单数据
    id: function() {
      this.fetch()
    }
  },
  created() {
    this.fetch()
    // 机动人员
    userList({ 's_roleCode': 'backup' }).then(res => {
      this.availableUsers = res.data.map(e => { return { name: e.name, username: e.username } })
    })
    // 驻场人员
    userList({ 's_roleIn': 'worker,bigdataBureau' }).then(res => {
      this.availableResidentUsers = res.data.map(e => { return { name: e.name, username: e.username } })
    })
  },
  methods: {
    // 初始化表单数据
    fetch() {
      if (this.id !== -1) {
        detail(this.id).then(response => {
          const { id, name, code, residents, users, lng, lat } = response.data
          const residentCodeArray = (residents || []).map(e => e.username)
          const userCodes = (users || []).map(e => e.username)
          this.formItem = { id, name, code, residentCodeArray, userCodes, lng, lat }
        })
      } else {
        this.formItem = {
          ...formItem
        }
      }
    },
    // 保存操作，返回promise，后续处理交由调用者处理
    save() {
      const updated = this.id !== -1
      return new Promise(resolve => {
        this.$refs.myform.validate((valid) => {
          if (valid) {
            const { name, code, residentCodeArray, userCodes, lng, lat } = this.formItem
            if (residentCodeArray && userCodes) {
              const filterData = userCodes.filter(e => residentCodeArray.includes(e))
              if (filterData.length > 0) {
                this.$message({
                  showClose: true,
                  message: '机动人员和驻场人员不能重复!',
                  type: 'error'
                })
                return resolve(false)
              }
            }

            // // 驻场人员名称
            // const filterData = this.availableResidentUsers.filter(e => e.username === residentUserCode)
            // const residentUserName = filterData.length > 0 ? filterData[0].name : ''
            const residents = this.availableResidentUsers.filter(e => residentCodeArray.indexOf(e.username) > -1).map(e => { return { name: e.name, username: e.username } })
            // 机动人员名称
            const users = this.availableUsers.filter(e => userCodes.indexOf(e.username) > -1).map(e => { return { name: e.name, username: e.username } })
            const saveData = { name, code, residents, users, lng, lat }

            if (updated) {
              resolve(update(this.id, saveData))
            } else {
              resolve(create(saveData))
            }
          } else {
            resolve(false)
          }
        })
      })
    },
    reset() {
      this.$refs.myform.resetFields()
    }
  }
}
</script>
